package com.lq.demo.demo.mode.mycache;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CacheListener {

    private final Logger logger = LoggerFactory.getLogger(CacheListener.class);

    private ICacheManager cacheManager;

    private ExecutorService executorService;

    public CacheListener(ICacheManager cacheManager) {
        this.cacheManager = cacheManager;
        executorService= Executors.newSingleThreadExecutor();
        startListen();
    }

    public ICacheManager getCacheManager() {
        return cacheManager;
    }

    public void setCacheManager(ICacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    private Runnable startListen() {
        if (cacheManager == null) return null;

        Thread thread = new Thread(() -> {
            while (true) {
                if(cacheManager.getSize()<=0)break;
                Set allKeys = cacheManager.getAllKeys();
                Iterator iterator = allKeys.iterator();
                while (iterator.hasNext()) {
                    Object key = iterator.next();
                    if (cacheManager.isTimeOut(key)) {
                        iterator.remove();
                        logger.info(key + "is  be   clear  now......");
                    }
                }
//                try {
//                    Thread.sleep(300);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        });
        executorService.execute(thread);
        return  thread;
    }

//    public void  start(){
//        Thread thread = (Thread) startListen();
//        executorService.execute(thread);
//    }
    public  void shutdown(){

        executorService.shutdownNow();
    }
}
